package student.mindmap.core.model;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.awt.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import static org.junit.jupiter.api.Assertions.*;

class PersistenceTest {
    private static final String TEST_FILE = "test_map.json";
    private MindMap originalMap;

    @BeforeEach
    void setup() {
        originalMap = new MindMap();
        originalMap.createNewMap("测试导图");

        MindMapNode node1 = new MindMapNode("一级节点");
        MindMapNode node2 = new MindMapNode("二级节点");

        originalMap.getRoot().addChild(node1);
        node1.addChild(node2);
        originalMap.registerNode(node1);
        originalMap.registerNode(node2);
    }

    @AfterEach
    void cleanup() throws IOException {
        Files.deleteIfExists(Path.of(TEST_FILE));
    }

    @Test
    void testSaveAndLoad() throws IOException {
        // 保存测试
        MindMapPersistence.saveToFile(originalMap, TEST_FILE);
        assertTrue(Files.exists(Path.of(TEST_FILE)));

        // 加载测试
        MindMap loadedMap = MindMapPersistence.loadFromFile(TEST_FILE);

        // 验证基础结构
        assertEquals(3, loadedMap.getAllNodes().size());
        assertEquals("测试导图", loadedMap.getRoot().getText());

        // 验证节点关系
        MindMapNode loadedRoot = loadedMap.getRoot();
        assertEquals(1, loadedRoot.getChildren().size());

        MindMapNode loadedChild = loadedRoot.getChildren().getFirst();
        assertEquals("一级节点", loadedChild.getText());
        assertEquals(1, loadedChild.getChildren().size());
    }

    @Test
    void testGraphicalProperties() throws IOException {
        // 设置图形属性
        MindMapNode node = originalMap.getRoot().getChildren().getFirst();
        node.setPosition(new Point(100, 200));

        // 保存并重新加载
        MindMapPersistence.saveToFile(originalMap, TEST_FILE);
        MindMap loadedMap = MindMapPersistence.loadFromFile(TEST_FILE);

        // 验证图形属性
        MindMapNode loadedNode = loadedMap.findNodeById(node.getId());
        assertEquals(new Point(100, 200), loadedNode.getPosition());
    }

    @Test
    void testNodeRegistration() {
        assertEquals(3, originalMap.getAllNodes().size()); // 根节点+node1+node2
    }
}